package deustotech.mobility.vc.core;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Vector;

import deustotech.mobility.vc.display.MenuFrame;

public class Controller {

	private static Controller c;
	private InetAddress localh;
	private InetAddress gateway;
	private ServidorGeoCast sGC;
	private MenuFrame mF;
	private ThreadWindow tW;
	private Vector<ServidorUniCast> vSU;
	private ServidorUniCast suc;
	private UnicastListener uL;

	private Controller(){
		c = this;	
		try {
			byte a [] = new byte[4];
			a[0]= (byte)192;
			a[1]= (byte)0;
			a[2]= (byte)5;
			a[3]= (byte)254;
			localh = InetAddress.getByAddress(a);
			byte b[] = localh.getAddress();
			b[3]= (byte) 129;

			gateway = InetAddress.getByAddress(b);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}

		System.out.println(localh);
		System.out.println(gateway);

		tW = new ThreadWindow();
		tW.start();
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		mF = tW.getMenuFrame();
		mF.post("Controller controlling!");

		sGC = ServidorGeoCast.getInstance();
		sGC.start();
		uL = UnicastListener.getInstance();
		uL.start();


		//		sUC = ServidorUniCast.getInstance();
		//		sUC.start();




		//		Timer t = new Timer(1000);
		//		t.start();
	}


	public static Controller getInstance() {
		if (c == null)
			c = new Controller();
		return c;
	}

	public InetAddress getGateway(){
		return gateway;
	}

	public InetAddress getLocalHost() {

		return localh;
	}


	public ServidorGeoCast getsGC() {
		return sGC;
	}


	public void setsGC(ServidorGeoCast sGC) {
		this.sGC = sGC;
	}

	public MenuFrame getmF() {
		return mF;
	}


	public void setmF(MenuFrame mF) {
		this.mF = mF;
	}


	public void pararUnicastServer(String dir) {
		suc.getJitter("/home/iigo/workspace/Timing/logs/logJitter.log");
		suc.setConnected(false);
		System.out.println("dir : "+dir);
//		for(int i = 0; i< vSU.size(); i++){
//			if(vSU.get(i).getDir().equals(dir)){
//				System.out.println("i "+vSU.get(i).getDir());
//				vSU.get(i).setConnected(false);
//				vSU.get(i).getJitter("/home/iigo/workspace/Timing/logs/logJitter.log");
//				System.out.println("Servidor en "+dir+" parado");
//			}
//		}

	}


	public void lanzarUnicastServer(String dir) {
//		if(vSU ==null)
//			vSU = new Vector<ServidorUniCast>();
//		boolean found = false;
//		for(int i = 0; i<vSU.size(); i++)
//			if(vSU.get(i).getDir().equals(dir))
//				found =true;
//		if(!found){
		suc = new ServidorUniCast(dir);
		suc.start();
//		vSU.add(suc);
//		}
	}

}
